<template>
    <div style=" position: relative;">
        <el-card>
            <template #header>
                <!-- 搜索 -->
                <div style="width:100%;display: flex;">
                    <div style="margin-right:20px">
                        <el-date-picker style="width: 350px;" v-model="data_time" @change="datetime_btn"
                            type="datetimerange" start-placeholder="开始时间" end-placeholder="结束时间"
                            format="YYYY-MM-DD HH:mm:ss" />
                    </div>
                    <div style="margin-right:20px">
                        <el-input style="width: 260px;" v-model="getWalletListForBack_find_data.find"
                            placeholder="请输入客户名称电话、单位名称" clearable prefix-icon="User" />
                    </div>
                    <div> <el-select  style="width: 260px;" v-model="getWalletListForBack_find_data.payType" placeholder="请选择交易类型" clearable>
                            <el-option v-for="item in getTradeTypes_list" :key="item.id" :label="item.text"
                                :value="item.id" />
                        </el-select>
                    </div>
                    <div>
                        <el-button style="margin-left: 20px;height:30px" @click="search_btn" type="primary"
                            icon="Search">搜索</el-button>
                    </div>
                </div>
                <!-- 功能按钮 -->
                <div style="margin-top:10px;">
                    <el-button @click="ex_getWalletListForBack_btn" type="warning" icon="Share">导出</el-button>
                </div>
            </template>
            <div>
                <el-table border @selection-change="selection_change_btn" height="67vh" ref="multipleTableRef"
                    :data="getWalletListForBack_list_data" style="width: 100%">
                    <el-table-column type="selection" width="35" />
                    <el-table-column label="编号" width="55" fixed type="index" />

                    <template v-for="item in table_data_list_new" :key="item.field">
                        <el-table-column v-if="item.off" :width="item.width" :prop="item.field" :label="item.label">
                            <template v-if="item.field == 'payType'" #="{ row, column, $index }">
                                <span>{{payTypeapi(row.payType) }}</span>
                            </template>

                            <template v-if="item.field == 'tradeStatus'" #="{ row, column, $index }">
                                <span>{{ row.tradeStatus == 'INCOME' ? '收入' : '支出' }}</span>
                            </template>
                            <!-- <template v-if="item.field == 'balType'" #="{ row, column, $index }">
                                {{ balType_api(row.balType) }}
                            </template> -->
                         

                        </el-table-column>
                    </template>
                </el-table>
            </div>

            <div style="margin-top:20px">
                <el-pagination @current-change="current_change_btn" @size-change="size_change_btn"
                    v-model:current-page="getWalletListForBack_find_data.page.pageNum"
                    v-model:page-size="getWalletListForBack_find_data.page.pageSize" :page-sizes="[20, 50, 100, 200]"
                    :background="true" layout="prev, pager, next, jumper,->,sizes,total," :total="total" />
            </div>
        </el-card>
    </div>
    <!-- 弹窗 -->
    <div>
        <!-- 表格筛选 -->
        <div style="position: absolute;top:75px;z-index: 2;" :style="icon_off ? 'right:0px;' : 'right:110px;'">
            <el-icon @click="icon_btn" :size="20">
                <Setting />
            </el-icon>
            <div v-show="icon_off"
                style=" position: relative;top:-100px;right:140px;width: 130px;height:430px;background:#fff;overflow: hidden;">
                <div class="cols-set" style="background:#fff;width:90%;height:97%;margin:auto;margin-top:10px;">
                    <div>
                        <el-button-group style="display: flex; ">
                            <el-tooltip effect="dark" placement="bottom">
                                <template #content>注意：拖动下面的项，可以改变表格列的顺序，<br />记得点击保存才会永久生效哦！ </template>
                                <el-button style="width:10px" type="primary" icon="WarningFilled"></el-button>
                            </el-tooltip>
                            <el-button title="重置" type="primary" icon="Refresh" @click="resetTableSet"></el-button>
                            <el-button title="保存" type="primary" icon="Check" @click="saveTableSet"></el-button>
                        </el-button-group>
                        <div ref="sortableContainer" class="col-items" style="height:400px; overflow-y: auto; ">
                            <el-checkbox class="drag_it" @change="checkbox_btn" v-for="item in sortedItems"
                                :key="item.field" v-model="item.off" :label="item.label" border>
                            </el-checkbox>
                        </div>

                    </div>
                </div>
            </div>
        </div>
    </div>
</template>

<script setup>
import Sortable from 'sortablejs';
import { ref, reactive, onMounted, computed } from 'vue'
import CircularJSON from 'circular-json'
import { getWalletListForBack, getTradeTypes, expWalletList, adupPrivateSet, getPrivateSetList } from '@/api/customer_list.js'
import * as XLSX from 'xlsx';
onMounted(async () => {
    let basic_settings = JSON.parse(localStorage.getItem('basic_settings'))
    if (basic_settings) {
        // data_time.value = [1, 2]
        getWalletListForBack_find_data.stime = ''
        getWalletListForBack_find_data.etime = ''
        getWalletListForBack_find_data.find = basic_settings.find
        getWalletListForBack_find_data.payType = basic_settings.payType
    }
    getPrivateSetList({
        find: '交易列表记录',
        page: {
            pageNum: 1,
            pageSize: 999,
        },
    }).then(res => {
        if (res.data.list[0]) {
            table_data_list_new.value = JSON.parse(res.data.list[res.data.list.length - 1].dat)
        } else {
            table_data_list_new.value = table_data_list
        }
    })
   

    Sortable.create(sortableContainer.value, {
        draggable: '.drag_it',
        ghostClass: 'sortable-ghost',
        onEnd: evt => {
            const targetRow = table_data_list_new.value.splice(evt.oldIndex, 1)[0];
            table_data_list_new.value.splice(evt.newIndex, 0, targetRow);

            // 重新赋值给列数组
            // let cols = that.U.scopy(that.fields);
            // let list = cols.filter(it => { return it.show; });
            // that.$emit('saveSet', {dgName: that.dgName, cols: list});
        }
    })


    await getWalletListForBack_list()
    await getTradeTypes_api()
})
//#region 表格数据处理
const table_data_list = reactive([
    { label: '姓名', field: 'realName', width: 85, off: true },
    { label: '交易账户', field: 'loginPhone', width: 120, off: true },
    { label: '单位名称', field: 'companyName', width: 200, off: true },
    { label: '交易类型', field: 'payType', width: 120, off: true },
    // { label: '交易账户', field: 'balType', width: 120, off: true },
    { label: '交易状态', field: 'tradeStatus', width: 100, off: true },
    { label: '交易金额', field: 'amoney', width: 100, off: true },
    { label: '交易后余额', field: 'cashBalance', width: 100, off: true },
    { label: '交易备注', field: 'note', width: 500, off: true },
    { label: '系统备注', field: 'assist', width: 500, off: true },
    { label: '交易时间', field: 'addTime', width: 165, off: true },
])

const table_data_list_new = ref([])
const icon_off = ref(false)
// 创建排序容器的引用
const sortableContainer = ref('')

const icon_btn = () => {
    icon_off.value = !icon_off.value
    console.log(sortableContainer.value)

}
const resetTableSet = () => {
    console.log(table_data_list)
    table_data_list_new.value = JSON.parse(JSON.stringify(table_data_list))
    console.log(table_data_list)
    console.log(table_data_list_new.value)
}
const saveTableSet = () => {
    adupPrivateSet({
        dat: JSON.stringify(table_data_list_new.value),
        tbName: '交易列表记录',
        tbNum: "basic_settings",
    }).then(res => {
        if (res.code == 1) {
            return ElMessage({
                message: res.msg,
                type: 'success',
            })
        } else {
            return ElMessage({
                message: res.msg,
                type: 'warning',
            })
        }
    })
    icon_off.value = false
}

const checkbox_btn = (e, c) => {
    for (let i = 0; i < table_data_list_new.value.length; i++) {
        if (table_data_list_new.value[i].label == c.target._value) {
            table_data_list_new.value[i].off == e

        }

    }

}

const sortedItems = computed(() => {
    return [...table_data_list_new.value].sort((a, b) => a.id - b.id);
})
//#endregion



//#region 分页列表
const getWalletListForBack_list_data = ref([])
const getWalletListForBack_find_data = reactive({
    page: {
        pageNum: 1,
        pageSize: 20,
    },
    stime: "",
    etime: "",
    find: "",
    payType: "",

})
const total = ref(0)

// 分页器一夜显示多少数据页面
const size_change_btn = () => {
    getWalletListForBack_find_data.page.pageNum = 1
    getWalletListForBack_list()
}

// 分页器跳转页面
const current_change_btn = () => {
    getWalletListForBack_list()
}

const getWalletListForBack_list = () => {

    getWalletListForBack(getWalletListForBack_find_data).then(res => {
        getWalletListForBack_list_data.value = res.data.list.list
        total.value = res.data.list.total
    })
}
//#endregion

//#region 表格选择
const table_list = ref([])
const selection_change_btn = (e) => {
    table_list.value = e
    console.log('表格选择的数据', e)
}
//#endregion

//#region 搜索
const data_time = ref('')
const datetime_btn = (e, y, c) => {
    const dateStr = e[0];
    const date = new Date(dateStr);
    const formattedDate = `${date.getFullYear()}-${(date.getMonth() + 1).toString().padStart(2, '0')}-${date.getDate().toString().padStart(2, '0')} ${date.getHours().toString().padStart(2, '0')}:${date.getMinutes().toString().padStart(2, '0')}:${date.getSeconds().toString().padStart(2, '0')}`;

    const dateStr2 = e[1];
    const date2 = new Date(dateStr2);
    const formattedDate2 = `${date2.getFullYear()}-${(date2.getMonth() + 1).toString().padStart(2, '0')}-${date2.getDate().toString().padStart(2, '0')} ${date2.getHours().toString().padStart(2, '0')}:${date2.getMinutes().toString().padStart(2, '0')}:${date2.getSeconds().toString().padStart(2, '0')}`;
    getWalletListForBack_find_data.stime = formattedDate
    getWalletListForBack_find_data.etime = formattedDate2

}

// 交易类型
const getTradeTypes_list = ref([])
const payTypeapi = (e) =>{
    for (let i = 0; i < getTradeTypes_list.value.length;i++){
        if (e ==getTradeTypes_list.value[i].id ) {
            return getTradeTypes_list.value[i].text
        }
    }
} 
const getTradeTypes_api = () => {
    getTradeTypes({}).then(res => {
        getTradeTypes_list.value = res.data
    })
}

const search_btn = () => {
    localStorage.setItem('basic_settings', CircularJSON.stringify(getWalletListForBack_find_data))
    getWalletListForBack_list()
}
//#endregion
//#region 交易记录列表导出
const ex_getWalletListForBack_btn = () => {
    expWalletList(getWalletListForBack_find_data).then(res => {
        if (res.code == 1) {
            const data = [
                ['客户名称', '客户电话', '单位名称', '交易类型', '交易状态', '交易金额', '交易后余额', '交易备注', '添加时间'],
            ];
            for (let i = 0; i < res.data.length; i++) {
                let ps = {
                    realName: res.data[i].realName,
                    loginPhone: res.data[i].loginPhone,
                    companyName: res.data[i].companyName,
                    payType: res.data[i].payType == 'ORDER_PAY' ? '订单付款' : res.data[i].payType == 'ORDER_REFUND' ? '订单退款' : res.data[i].payType == 'FALSIFY_MONEY' ? '违约金' : res.data[i].payType == 'TRANSFER_ACCOUNTS' ? '转账' : res.data[i].payType == 'BALANCE_RECH' ? '余额充值' : res.data[i].payType == 'POINT_REWARD' ? '巴士币提成' : res.data[i].payType == 'SET_CREDIT_BALANCE' ? '信用额度调整' : res.data[i].payType == 'WITHDRAW_CASH' ? '余额提现' : '余额提现手续费',
                    tradeStatus: res.data[i].tradeStatus == 'INCOME' ? '收入' : '支出',
                    amoney: res.data[i].amoney,
                    cashBalance: res.data[i].cashBalance,
                    note: res.data[i].note,
                    addTime: res.data[i].addTime,

                }
                data.push(Object.values(ps))
            }
            const ws = XLSX.utils.aoa_to_sheet(data);
            const wb = XLSX.utils.book_new();
            XLSX.utils.book_append_sheet(wb, ws, 'Sheet1');
            XLSX.writeFile(wb, '客车帮服务后台系统管理-交易记录列表.xlsx');
            findCusWalletPages_list()
            return ElMessage({
                message: res.msg,
                type: 'success',
            })
        } else {
            return ElMessage({
                message: res.msg,
                type: 'warning',
            })
        }

    })
}
//#endregion
</script>

<style scoped lang='scss'>
</style>

<style>
.col-items::-webkit-scrollbar {
    width: 5px !important;
}

.col-items>label {
    margin-left: 0px !important;
    margin-top: 5px;
    width: 100%;
}

.el-table .el-table__cell {
    padding: 0px !important;
}
</style>
